#include "globalmouse.h"
#include <QDebug>
#include <QCoreApplication>
#include <X11/Xlib.h>
#include <stdio.h>

GlobalMouse::GlobalMouse()
{
    onOff = false;
}

GlobalMouse::~GlobalMouse()
{
}

void GlobalMouse::setCursorOn()
{
    onOff = true;
}

void GlobalMouse::setCursorOff()
{
    onOff = false;
}

void GlobalMouse::mousePressed()
{
    Display* display;
    Window root;
    display = XOpenDisplay( NULL );
    root = DefaultRootWindow( display);
    Window root_return, child_return;
    int x, y;
    int win_x, win_y;
    unsigned int mask;
    int pressed = 0;

    while( onOff )
    {
        QCoreApplication::processEvents( QEventLoop::AllEvents );
        XQueryPointer(display, root, &root_return, &child_return, &x, &y, &win_x, &win_y, &mask);
        if ((m_oldx != x) || (m_oldy != y))
        {
            emit mousemove( x, y);

            m_oldx = x;
            m_oldy = y;
        }

        if ((mask & Button1Mask) | (mask & Button2Mask) | (mask & Button3Mask))
        {
            if ( pressed == 0 )
            {
                pressed = 1;
                emit mousePressed( win_x, win_y );
            }
        }
        else
        {
            pressed = 0;
        }

        fflush(stdout);
    }
    XCloseDisplay( display );
}
